<template>
    <div class="root" ref="root">
        <div class="welcome-words">
            <div :class="['wel-word-one', isMobile ? 'mobile-wel-word-one' : 'null']">
                <span>您好~</span>
            </div>
            <div :class="['wel-word-two', isMobile ? 'mobile-wel-word-two' : 'null']">
                <span>欢迎使用时间胶囊</span>
            </div>
        </div>
        <div class="login-way">
            <div class="login-wby" @click="changeWay(0)">
                <span>TwT登录</span>
            </div>
            <div class="part-line">|</div>
            <div class="login-email" @click="changeWay(1)">
                <span>邮箱登录</span>
            </div>
            <div class="now-select"></div>
        </div>
        <div :class="['user-account',isMobile ? 'mobile-input-acc' : 'null']">
            <el-form :model="twtLogin" @submit.native.prevent>
                <el-form-item prop="account" :rules="[{ required:true, message:'用户名不能为空' }]" v-show="nowLeft == '0.45333rem'">
                    <el-input
                        v-model="twtLogin.account"
                        class="account"
                        placeholder="请输入您的TWT账户"
                        :prefix-icon="User"
                        clearable
                        :size= "isMobile ? 'large' : 'default'"
                        @keyup.enter.native="triggerLogin()"
                    />
                </el-form-item>
            </el-form>
            <el-form :model="emailLogin" @submit.native.prevent>
                <el-form-item prop="email" :rules="[{ required:true, message:'邮箱不能为空' }]" v-show="nowLeft == '4.02667rem'">
                    <el-input
                        v-model="emailLogin.email"
                        class="account"
                        placeholder="请输入您的邮箱"
                        :prefix-icon="User"
                        clearable
                        :size= "isMobile ? 'large' : 'default'"
                        @keyup.enter.native="triggerLogin()"
                    />
                </el-form-item>
            </el-form>
        </div>
        <div :class="['user-pwd',isMobile ? 'mobile-input-pwd' : 'null']">
            <el-form :model="twtLogin" @submit.native.prevent>
                <el-form-item prop="password" :rules="[{ required:true, message:'密码不能为空' }]" v-show="nowLeft == '0.45333rem'">
                    <el-input
                        v-model="twtLogin.password"
                        placeholder="请输入密码"
                        :prefix-icon="Lock"
                        clearable
                        show-password
                        :size= "isMobile ? 'large' : 'default'"
                        @keyup.enter.native="triggerLogin()"
                    />
                </el-form-item>
            </el-form>
            <el-form :model="emailLogin" @submit.native.prevent>
                <el-form-item prop="password" :rules="[{ required:true, message:'密码不能为空' }]" v-show="nowLeft == '4.02667rem'">
                    <el-input
                        v-model="emailLogin.password"
                        placeholder="请输入密码"
                        :prefix-icon="Lock"
                        clearable
                        show-password
                        :size= "isMobile ? 'large' : 'default'"
                        @keyup.enter.native="triggerLogin()"
                    />
                </el-form-item>
            </el-form>
            <div class="lost-key-wrapper">
                <div class="lost-key" @click="changeEmail()">
                    <span>忘记密码？</span>
                </div>
            </div>
        </div>
        <div class="login-btn-wrapper">
            <el-button class="login-btn" round :size= "isMobile ? 'large' : 'default'" @click="triggerLogin()">登录</el-button>
        </div>
    </div>
    <van-dialog v-model:show="showConfirmEmail" title="我们将向该邮箱发送邮件" show-cancel-button confirm-button-text="使用该邮箱" cancel-button-text="更改邮箱" @confirm="loginCapsual()" @cancel="changeEmail()" closeOnClickOverlay>
        <div style="fontSize: 15px; margin: 8px 6px 8px 6px; textAlign: center;">
            <span>{{ userEmail }}</span>
        </div>
        <div style="fontSize: 15px; margin: 8px 6px 8px 6px; textAlign: center;">
            <span>可更改收件邮箱</span>
        </div>
        <div style="fontSize: 15px; margin: 8px 6px 8px 6px; textAlign: center;">
            <span>注意：与天外天账号绑定的邮箱将同步更新</span>
        </div>
    </van-dialog>
    <van-dialog v-model:show="showChangeEmail" show-cancel-button confirm-button-text="确认" v-model:cancel-button-text="valiCodeNum" @cancel="launchCode()" @confirm="!isLogined ? findUserPassword() : signInEmail()" closeOnClickOverlay :before-close="beforeClose">
        <van-form>
            <van-field
                v-model="emailInfo.email"
                label="邮箱"
                placeholder="请输入要绑定的邮箱"
                required
                :rules="[{ required: true, validator, message: '邮箱不可为空' }]"
                clearable
                label-width="5em"
            />
            <van-field
                v-model="emailInfo.password"
                label="密码"
                type="password"
                placeholder="请设置密码"
                required
                :rules="[{ required: true, validator, message: '密码不可为空' }]"
                clearable
                label-width="5em"
            />
            <van-field
                v-model="emailInfo.passwordConfirm"
                label="确认密码"
                type="password"
                placeholder="请再次确认密码"
                required
                :rules="[{ required: true, validator, message: '确认密码不可为空' }]"
                clearable
                label-width="5em"
            />
            <van-field
                v-model="emailInfo.code"
                label="验证码"
                placeholder="请输入验证码"
                required
                :rules="[{ required: true, validator,message: '验证码不可为空' }]"
                clearable
                label-width="5em"
            />
        </van-form>
    </van-dialog>
</template>

<script lang="ts" setup>
import { ref,computed,onMounted,reactive,watch } from "vue";
import { User,Lock } from "@element-plus/icons-vue";
import { useGlobalData } from '../store/index';
import { twt_login,Wby_login,email_login,getEmailCode,registerEmail,findPassword } from '../request/api';
import { ElMessage,ElLoading } from 'element-plus';
import { setToken } from "../request/cookies";
import { useRouter } from "vue-router";
interface TwtLogin{
    account: string,
    password: string,
}
interface EmailLogin{
    email: string,
    password: string,
}
interface EmailInfo{
    email: string,
    password: string,
    passwordConfirm: string,
    code: string,
    nickName?: string
}
interface Options {
    lock: boolean,
    text: string,
    background: string,
}
const options: Options = {
    lock: true,
    text: "Loading...",
    background: 'rgba(0,0,0,0.7)'
}
const GlobalData = useGlobalData();
const root = ref<HTMLElement>();
const nowSelectFlag = ref<number>(0);  //0表示TwT账户，1表示邮箱
const showConfirmEmail = ref<boolean>(false);
const showChangeEmail = ref<boolean>(false);
const userEmail = ref<string>("");
const isLogined = ref<boolean>(false);
const router = useRouter();
const userNickName = ref<string>("");
const wordOneColor = ref<string>("#523f3f");
const wordTwoColor = ref<string>("rgb(244, 229, 229)");
const nowLeft = ref<string>("0.45333rem");
const valiCodeNum = ref<string>('发送验证码');  //验证码发送倒计时
const isCountDownOk = ref<boolean>(true);  //倒计时是否结束
const twtLogin = reactive<TwtLogin>({
    account: "",
    password: "",
})
const emailLogin = reactive<EmailLogin>({
    email: "",
    password: "",
})
var emailInfo = reactive<EmailInfo>({
    email: "",
    password: "",
    passwordConfirm: "",
    code: "",
})
const nowToken = reactive({
    token: "",
})
const header = {
    ticket: 'YmFuYW5hLjM3YjU5MDA2M2Q1OTM3MTY0MDVhMmM1YTM4MmIxMTMwYjI4YmY4YTc=',
    domain: 'weipeiyang.twt.edu.cn',
    'Content-Type': 'application/x-www-form-urlencoded'
}
var isMobile = computed(() => {
    return GlobalData.width < 651;
})
const handleResize = () => {
    GlobalData.width = root.value?.clientWidth as number;
    GlobalData.height = root.value?.clientHeight as number;
}
const isNull = (str:string) => {
    if(str == "") return true;
    let regu = "^[ ]+$";
    let re = new RegExp(regu);
    return re.test(str);
}
const beforeClose = (action:any) => {
    if(action == 'cancel' && isCountDownOk.value == false){
        return false;
    }else return true;
}
const triggerLogin = () => {
    if((nowLeft.value === '0.45333rem' && (isNull(twtLogin.account) || isNull(twtLogin.password))) || (nowLeft.value === '4.02667rem' && (isNull(emailLogin.email) || isNull(emailLogin.password)))){
        ElMessage.error("账密不能为空");
    }else if(nowLeft.value === '0.45333rem'){
        twt_login(twtLogin,header).then((res:any) => {
            console.log(res);
            console.log(res.result.token);
            userEmail.value = res.result.email;
            GlobalData.nickName = res.result.nickname;
            GlobalData.uid = res.result.userNumber;
            nowToken.token = res.result.token;
            Wby_login(nowToken).then((res:any) => {
                console.log(res);
                setToken(res.result.token); //登录成功
                if(res.error_code == 0){
                    ElMessage.success('登录成功');
                    isLogined.value = true;  //登录了
                    showConfirmEmail.value = true;
                    GlobalData.role = res.result.role[0];
                    emailInfo.code = "";
                    emailInfo.email = "";
                    emailInfo.password = "";
                    emailInfo.passwordConfirm = "";
                }
            })
        })
    }else if(nowLeft.value === '4.02667rem'){   //使用邮箱登录
        email_login(emailLogin).then((res:any) => {
            console.log(res);
            if(res && res.error_code == 0){
                setToken(res.result.token);
                ElMessage.success('登录成功');
                isLogined.value = true;  //登录了
                userEmail.value = emailLogin.email;
                GlobalData.nickName = res.result.nickname;
                GlobalData.uid = res.result.userNumber;
                GlobalData.role = res.result.role[0];
                showConfirmEmail.value = true;
                emailInfo.code = "";
                emailInfo.email = "";
                emailInfo.password = "";
                emailInfo.passwordConfirm = "";
            }
        })
    }
}
const validator = (val:string) => val!="";
const loginCapsual = () => {
    router.push({
        name: 'capsual',
    })
}
const changeEmail = () => {
    showChangeEmail.value = true;
}
const changeWay = (flag:number) => { //flag表示选择的是哪个
    if(nowSelectFlag.value === 0 && flag === 1){ //要切换为邮箱
        nowSelectFlag.value = 1;
        nowLeft.value = '4.02667rem';
        wordOneColor.value = 'rgb(244, 229, 229)';
        wordTwoColor.value = '#523f3f';
        [twtLogin.account, twtLogin.password] = ["", ""];
    }else if(nowSelectFlag.value === 1 && flag === 0){
        nowSelectFlag.value = 0;
        nowLeft.value = '0.45333rem';
        wordTwoColor.value = 'rgb(244, 229, 229)';
        wordOneColor.value = '#523f3f';
        [twtLogin.account, twtLogin.password] = ["", ""];
    }
}
const launchCode = () => {
    if(!isCountDownOk.value) return;
    let countDownNum:number = 60;
    let loading = ElLoading.service(options);
    getEmailCode({email: emailInfo.email}).then((res:any) => {
        console.log(res);
        loading.close();
        if(res==undefined) return;
        isCountDownOk.value = false;
        showChangeEmail.value = true;
        ElMessage.success('发送成功');
        let time_set = setInterval(() => {
            countDownNum--;
            valiCodeNum.value = '发送验证码';
            if(countDownNum == 0) clearInterval(time_set),isCountDownOk.value = true;
            valiCodeNum.value += `(${countDownNum})`;
        },1000);
    })
}
const findUserPassword = () => {
    console.log("findPassword");
    findPassword(emailInfo).then((res:any) => {
        console.log(res);
        if(res && res.error_code == 0){
            ElMessage.success("操作成功");
        }
    })
}
const signInEmail = () => {
    emailInfo.nickName = userNickName.value;
    console.log(emailInfo);
    registerEmail(emailInfo).then((res:any) => {
        console.log(res);
        if(res && res.error_code == 0){
            ElMessage.success("更改成功");
        }
    })
}
window.addEventListener('resize',() => handleResize());
watch(isCountDownOk,(newVal:boolean) => {
    if(newVal == true){
        valiCodeNum.value = '发送验证码';
    }
})
onMounted(() => {
    handleResize();
})
</script>

<style lang="less">
.el-input{
    --el-input-border-radius: 100px !important;
}
</style>
<style lang="less" scoped>
.root{
    background-image: linear-gradient(135deg,#fff,#55ccc9,#2cada8,#0a4947);
    height: 100%;
    padding-top: 145px;
    overflow: hidden;
    .login-way{
        position: relative;
        display: flex;
        justify-content: center;
        width: 200px;
        margin: 0 auto;
        margin-top: 10px;
        font-size: 13px;
        .login-wby{
            margin-right: 40px;
            cursor: pointer;
            color: v-bind(wordOneColor);
        }
        .part-line{
            color: rgb(244, 229, 229);
        }
        .login-email{
            margin-left: 40px;
            cursor: pointer;
            color: v-bind(wordTwoColor);
        }
        .now-select{
            background-color: rgb(244, 229, 229);
            width: 30px;
            height: 1.5px;
            position: absolute;
            top: 20px;
            left: v-bind(nowLeft); //0.45333rem,4.02667rem
            transition: left 0.7s;
        }
    }
    .welcome-words{
        display: flex;
        flex-direction: column;
        margin-left: 20px;
        color: rgb(244, 229, 229);
        .wel-word-one{
            width: 400px;
            align-self: center;
            font-size: 18px;
        }
        .wel-word-two{
            width: 400px;
            align-self: center;
            font-size: 18px;
            font-weight: bold;
        }
    }
    .user-account{
        width: 400px;
        margin: 0 auto;
        margin-top: 20px;
    }
    .user-pwd{
        width: 400px;
        margin: 0 auto;
        margin-top: 15px;
        .lost-key-wrapper{
            display: flex;
            width: 100%;
            flex-direction: row-reverse;
            .lost-key{
                color: rgb(244, 229, 229);
                cursor: pointer;
            }
        }
    }
    .login-btn-wrapper{
        display: flex;
        justify-content: center;
        margin-top: 4px;
        .login-btn{
            width: 100px;
            background-color: rgb(82, 63, 63);
            color: rgb(244, 229, 229);
            box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.4);
            border: none;
        }
    }
    .mobile-wel-word-one{
        width: 75% !important;
        margin-top: 30px;
    }
    .mobile-wel-word-two{
        width: 75% !important;
    }
    .mobile-input-acc{
        width: 70%;
    }
    .mobile-input-pwd{
        width: 70%;
        margin-top: 18px;
    }
    .null{
        width: 400px;
    }
}
</style>